from fastapi import APIRouter, HTTPException, Depends
from typing import List
from sqlalchemy.orm import Session
from schema import Plot_Crop_schema
from controller import Plot_Crop_controller
from database.db_init import get_db


router = APIRouter()


@router.post("/Plot_Crop", response_model=Plot_Crop_schema.Plot_crop, tags=["Plot_Crop"])
async def create_Plot_Crop(Plot_Crop: Plot_Crop_schema.Plot_crop, db: Session = Depends(get_db)):
    return Plot_Crop_controller.create_Plot_Crop(db, Plot_Crop)


@router.get("/Plot_Crop/{ID}", response_model=Plot_Crop_schema.Plot_crop, tags=["Plot_Crop"])
async def get_Plot_Crop(ID: int, db: Session = Depends(get_db)):
    db_Plot_Crop = Plot_Crop_controller.get_Plot_Crop(db, ID)
    if db_Plot_Crop is None:
        raise HTTPException(status_code=404, detail="Plot_Crop not found")
    return db_Plot_Crop


@router.get("/Plot_Crop", response_model=List[Plot_Crop_schema.Plot_crop], tags=["Plot_Crop"])
async def get_all_Plot_Crop(db: Session = Depends(get_db)):
    all_db_Plot_Crop = Plot_Crop_controller.get_all_Plot_Crop(db)
    if all_db_Plot_Crop is None:
        raise HTTPException(status_code=404, detail="0 Plot_Crop found, empty table")
    return all_db_Plot_Crop


@router.put("/Plot_Crop/{ID}", tags=["Plot_Crop"])
async def update_Plot_Crop(ID: int, field_name: str, field_value: str, db: Session = Depends(get_db)):
    try:
        db_Plot_Crop = Plot_Crop_controller.update_Plot_Crop(db, ID, field_name, field_value)
        if db_Plot_Crop is None:
            raise HTTPException(status_code=404, detail="Plot_Crop not found")
        return db_Plot_Crop
    except ValueError as error:
        raise HTTPException(status_code=400, detail=str(error))


@router.delete("/Plot_Crop/{ID}", tags=["Plot_Crop"])
async def delete_Plot_Crop(ID: int, db: Session = Depends(get_db)):
    is_deleted = Plot_Crop_controller.delete_Plot_Crop(db, ID)
    if is_deleted is None:
        raise HTTPException(status_code=404, detail=f'Sample {ID} does not exist in database')
    else:
        return {'message': f'Successfully delete sample {ID}'}
